package ma.cdm.Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Arrays;
import java.util.List;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
public class FileCompressions {

    /**
     * Compresses a file with zlib compression.
     */
    public static void compressFile(File raw, File compressed)
        throws IOException
    {
        InputStream in = new FileInputStream(raw);
        OutputStream out =
            new DeflaterOutputStream(new FileOutputStream(compressed));
        shovelInToOut(in, out);
        in.close();
        out.close();
    }

    /**
     * Decompresses a zlib compressed file.
     */
    public static void decompressFile(File compressed, File raw)
        throws IOException
    {
        InputStream in =
            new InflaterInputStream(new FileInputStream(compressed));
        OutputStream out = new FileOutputStream(raw);
        shovelInToOut(in, out);
        in.close();
        out.close();
    }

    /**
     * Shovels all data from an input stream to an output stream.
     */
    private static void shovelInToOut(InputStream in, OutputStream out)
        throws IOException
    {
        byte[] buffer = new byte[1000];
        int len;
        while((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
    }

    public static  List<File> unTar(final File fileTar, final File repertoire) throws Exception {

        ProcessBuilder pbTar =  new ProcessBuilder("7z.exe", "x", fileTar.getAbsolutePath());       
        pbTar.directory(repertoire);		
        pbTar.redirectErrorStream(true);
        
        Process procTar = pbTar.start();       
      
        Reader reader = new InputStreamReader(procTar.getInputStream());
        @SuppressWarnings("unused")
        int ch;
        while ((ch = reader.read()) != -1){}
           
        reader.close();
        procTar.waitFor();
        procTar.getInputStream().close();
        procTar.getErrorStream().close();
        procTar.getOutputStream().close();	
        
        File file = new File(repertoire.getAbsoluteFile()+"\\"+fileTar.getName().split("[.]")[0]);
        return  Arrays.asList(file.listFiles());
    }
    
    public static  List<File> decompress(final File file, final File repertoire) throws Exception {

        ProcessBuilder pb =  new ProcessBuilder("7z.exe", "x", file.getAbsolutePath());       
        pb.directory(repertoire);		
        pb.redirectErrorStream(true);
        
        Process proc = pb.start();       
      
        Reader reader = new InputStreamReader(proc.getInputStream());
        @SuppressWarnings("unused")
		int ch;
        while ((ch = reader.read()) != -1){}
           
        reader.close();
        proc.waitFor();
        proc.getInputStream().close();
        proc.getErrorStream().close();
        proc.getOutputStream().close();	      
       
        return  Arrays.asList(repertoire.listFiles());
    }
    public static File unGzip(final File fileGz, final File repertoire) throws Exception {

    	
		ProcessBuilder pbGz =  new ProcessBuilder("7z.exe", "x", fileGz.getAbsolutePath());		 
		pbGz.directory(repertoire);		
		pbGz.redirectErrorStream(true);
        Process procGz = pbGz.start();
        Reader reader = new InputStreamReader(procGz.getInputStream());
        @SuppressWarnings("unused")
        int ch;
        while ((ch = reader.read()) != -1){}
         
        reader.close();
        procGz.waitFor();
        procGz.getInputStream().close();
        procGz.getErrorStream().close();
        procGz.getOutputStream().close();
      
        for (File file : repertoire.listFiles()) {
			if(!file.isDirectory() && file.getName().endsWith(".tar"))
			{
				return file;
			}
		}
        
        return null;
    }
    
    private static final int TEMP_DIR_ATTEMPTS = 10000;
    
    public static File createTempDir() {
   	  File baseDir = new File(System.getProperty("java.io.tmpdir"));
   	  String baseName = System.currentTimeMillis() + "-";

   	  for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
   	    File tempDir = new File(baseDir, baseName + counter);
   	    if (tempDir.mkdir()) {
   	      return tempDir;
   	    }
   	  }
   	  throw new IllegalStateException("Failed to create directory within "
   	      + TEMP_DIR_ATTEMPTS + " attempts (tried "
   	      + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
   	}
    
    
//    public static void main(String[] args) throws IOException, DataFormatException {
//        File compressed = new File("D:\\scanDirs\\formules\\2_19403003598_820_194_TE_0477102_0000000299500_0000003317232_25_09_12");
//        compressFile(new File("D:\\scanDirs\\formules\\2_19403003598_820_194_TE_0477102_0000000299500_0000003317232_25_09_12.pdf"), compressed);
//        decompressFile(compressed, new File("D:\\scanDirs\\formules\\dddd2_19403003598_820_194_TE_0477102_0000000299500_0000003317232_25_09_12.pdf"));
//    }
    
    
}